package com.tpc.eb.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tpc.eb.bean.Main;
import com.tpc.eb.bean.MainBean;
import com.tpc.eb.utils.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.quartz.*;
import org.springframework.util.DigestUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.List;


@Slf4j
@DisallowConcurrentExecution
public class BusinessJobs extends Thread  implements Job {

    @SneakyThrows
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Connection connection = null;
        JSONObject jsonObjectRequest = new JSONObject();
        Map<String, Object> map = null;
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObjectNextNext = null;
        JSONObject jsonObjectNext = new JSONObject();
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        String params = jobDataMap.getString("params");
        JSONObject jsonObject = JSON.parseObject(params);
        String businessType = jsonObject.getString("BusinessType");
        String interfaceType = jsonObject.getString("InterfaceType");
        String code = jsonObject.getString("code");
        String node = jsonObject.getString("node");
        String PLAN = jsonObject.getString("PLAN");
        String BACKSQL = jsonObject.getString("BACKSQL");
        String PULLSQL = jsonObject.getString("PULLSQL");
        String URL = jsonObject.getString("URL");
        String AppKey = jsonObject.getString("AppKey");
        String AppSecret = jsonObject.getString("AppSecret");
        String Type = jsonObject.getString("Type");
        String AppType = jsonObject.getString("AppType");
        String Method = jsonObject.getString("Method");
        String SignNo = jsonObject.getString("SignNo");
        String Name = jsonObject.getString("Name");
        String timestamp = DateUtil.getNowDateNoInterval();
        String times = DateUtil.getNowDate();
        String tmp = AppKey+AppSecret+timestamp;
        tmp= DigestUtils.md5DigestAsHex(tmp.getBytes()).toUpperCase();
        String result = "";
        String errMsg = "";
        String info = "";
        info= DateUtil.getNowDate() + "---------" + businessType + "任务正在执行---------";
        log.info(info);
        OutputUtil.printLog(info);
        try {
            connection = JDBCUtil.getConnection();
            if (PULLSQL.trim().length() > 0) {
                QueryRunner queryRunner = new QueryRunner();
                map = queryRunner.query(connection, PULLSQL, new MapHandler());
                if (map != null) {
                    jsonObjectNext.put(node, map);
                    jsonObjectNext = JSONUtil.transToLowerObject(jsonObjectNext.toJSONString());
                }
            }
        } catch (Exception e) {
            errMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            JDBCUtil.close(connection);
        }
        if(errMsg.length()>0){
            info=DateUtil.getNowDate() + "---------" + businessType+code + "配置错误---------"+errMsg;
            log.info(info);
            OutputUtil.printLog(info);
            return;
        }
        if(map==null){
            info =DateUtil.getNowDate() + "---------" + businessType+code + "无请求数据---------";
            log.info(info);
            OutputUtil.printLog(info);
            return;
        }
        MainBean mainBean = new MainBean();
        mainBean.setInfno(code);
        mainBean.setMsgid(AppKey + timestamp + "00001");
        mainBean.setInf_time(times);
        mainBean.setFixmedins_code(AppKey);
        mainBean.setFixmedins_name(Name);
        mainBean.setSign_no(SignNo);

        JSONObject jsonObjectMain = (JSONObject) JSONObject.toJSON(mainBean);
        jsonObjectMain.put("info", jsonObjectNext);

        Main main = new Main();
        main.setAppid(AppKey);
        main.setMethod(Method);
        main.setTimestamp(timestamp);
        main.setSign(tmp);
        main.setBizContent(jsonObjectMain.toJSONString());
        jsonObjectRequest = (JSONObject) JSON.toJSON(main);
        String request = jsonObjectRequest.toJSONString();
        log.info(businessType + "请求JSON:{}", request);
        OutputUtil.printLog(DateUtil.getNowDate() + "---------" + businessType+code + "请求参数---------" + request);
        result = HTTPClient.sendHttpRequest(URL, request, 10000);
        log.info(businessType + "返回JSON:{}", result);
        OutputUtil.printLog(DateUtil.getNowDate() + "---------" + businessType+code + "返回参数--------" + result);
        String ID= (String) map.get("ID");
        String remark = times+" "+ result;
        String updateSQL = "update EB_"+code+" set updateTime='"+remark+"' where ID='"+ID+"'";
        log.info("updateSQL:{}",updateSQL);
        if(!JSONUtil.IsJSON(result)){
            try {
                connection = JDBCUtil.getConnection();
                connection.setAutoCommit(false);
                QueryRunner queryRunner = new QueryRunner();
                queryRunner.update(connection,updateSQL);
                connection.commit();
            } catch (Exception e) {
                try{
                    connection.rollback();
                }catch (SQLException sqlException){
                    e.printStackTrace();
                }
                errMsg = e.getMessage();
            } finally {
                JDBCUtil.close(connection);
            }
        }
        JSONObject jsonObjectResult = JSONObject.parseObject(result);
        if(jsonObjectResult.getString("code").equals("0")){
            String insertSQL = "insert into EB_"+code+"_His select * from EB_"+code+ " where ID= '"+ID + "'";
            String deleteSQL = "delete from EB_"+code + " where ID= '"+ID+"'";
            log.info("insertSQL:{}",insertSQL);
            log.info("deleteSQL:{}",deleteSQL);
            try {
                connection = JDBCUtil.getConnection();
                connection.setAutoCommit(false);
                QueryRunner queryRunner = new QueryRunner();
                queryRunner.update(connection,insertSQL);
                queryRunner.update(connection,deleteSQL);
                connection.commit();
            } catch (Exception e) {
                try{
                    connection.rollback();
                }catch (SQLException sqlException){
                    e.printStackTrace();
                }
                errMsg = e.getMessage();
            } finally {
                JDBCUtil.close(connection);
            }
        }else{
            try {
                connection = JDBCUtil.getConnection();
                connection.setAutoCommit(false);
                QueryRunner queryRunner = new QueryRunner();
                queryRunner.update(connection,updateSQL);
                connection.commit();
            } catch (Exception e) {
                try{
                    connection.rollback();
                }catch (SQLException sqlException){
                    e.printStackTrace();
                }
                errMsg = e.getMessage();
            } finally {
                JDBCUtil.close(connection);
            }
        }
        if(errMsg.length()>0){
            info = DateUtil.getNowDate() + "---------" + businessType+code + "配置错误--------" + errMsg;
            log.info(info);
            OutputUtil.printLog(info);
            return;
        }




        /*
        if(interfaceType.equals("Request")) {
            try {
                connection = JDBCUtil.getConnection();
                if (PULLSQL.trim().length() > 0) {
                    QueryRunner queryRunner = new QueryRunner();
                    list = queryRunner.query(connection, PULLSQL, new MapListHandler());
                    for(int i=0;i<list.size();i++){
                        jsonArray.add(list.get(i));
                    }
                }
                log.info("jsonArray:"+jsonArray.toJSONString());
                jsonArray = JSONUtil.transToArray(jsonArray.toJSONString());
                jsonObjectRequest.put("date",jsonArray);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                JDBCUtil.close(connection);
            }
        }else if(interfaceType.equals("Response")){
            JSONObject dateJSON = new JSONObject();
            dateJSON.put("action","fbWarehouseOrder");
            jsonObjectRequest.put("date",dateJSON);
        }
        String requestStr = jsonObjectRequest.toJSONString();
        log.info(businessType+"请求JSON:"+requestStr);
        String result = HTTPClient.sendHttpRequest(URL, requestStr, 10000);
        log.info(businessType+"返回JSON:"+result);
        boolean resultIsJSON = JSONUtil.IsJSON(result);
        if(resultIsJSON){
            List listParams = new ArrayList();
            if(interfaceType.equals("Request")){
                JSONObject resultJSON = JSON.parseObject(result);
                if(resultJSON.getString("code").equals("200")){
                    String[] split = BACKSQL.split("\\s+");
                    for(int i=0;i<split.length;i++){
                        String splitStr = split[i];
                        if(splitStr.indexOf(":")>-1){
                            BACKSQL = BACKSQL.replace(splitStr,"? ");
                            listParams.add(splitStr.replace(":","").toLowerCase());
                        }
                    }
                    int paramsCount = listParams.size();
                    if(paramsCount>0){
                        String writeBackParams = "[";
                        int jsonSize = jsonArray.size();
                        Object[][] objects = new Object[jsonSize][paramsCount];
                        for(int j=0;j<jsonSize;j++){
                            writeBackParams = writeBackParams + "[";
                            JSONObject jsonParams = jsonArray.getJSONObject(j);
                            for(int i=0;i<paramsCount;i++){
                                String paramsStr = (String) listParams.get(i);
                                String paramsString = jsonParams.getString(paramsStr) !=null ? jsonParams.getString(paramsStr) : "";
                                objects[j][i]=paramsString;
                                writeBackParams = writeBackParams + paramsString + ",";
                            }
                            writeBackParams = writeBackParams.substring(0,writeBackParams.length()-1) + "],";
                        }
                        writeBackParams = writeBackParams.substring(0,writeBackParams.length()-1) + "]";
                        try {
                            connection = JDBCUtil.getConnection();
                            QueryRunner queryRunner = new QueryRunner();
                            log.info("回写语句："+BACKSQL);
//                            String[] strings = Arrays.copyOf(objects, objects.length, String[].class);
                            log.info("回写参数："+writeBackParams);
                            queryRunner.batch(connection,BACKSQL,objects);
                        }catch (Exception e){
                            e.printStackTrace();
                        }finally {
                            JDBCUtil.close(connection);
                        }
                    }
                }
            }
        }
        */

//        OutputUtil.printLog(DateUtil.getNowDate() +"---------"+businessType+"任务返回信息---------"+"result"); //result

    }


}
